﻿using System.Net.Sockets;
using Jiubang.Communication.Server.DataTransport;
using Jiubang.Util;

namespace Jiubang.Communication.Common {
    /// <summary>
    ///   通信消息上下文，包含两部分内容:<br />
    ///   1、用于通信的Socket对象。<br />
    ///   2、用于保存消息内容的BufferSegment变量。
    /// </summary>
    public struct MessageContext {
        internal BufferSegment Segment;
        internal Socket Socket;

        public MessageContext(byte[] buffer) : this(new BufferSegment(buffer, 0), null) {}

        internal MessageContext(SocketAsyncEventArgs socketAsyncEventArgs) {
            Segment = new BufferSegment(socketAsyncEventArgs.Buffer, SocketServer.messageHeadLength);
            Socket = socketAsyncEventArgs.AcceptSocket;
        }

        internal MessageContext(BufferSegment segment, Socket socket) {
            Segment = segment;
            Socket = socket;
        }

        public byte this[int index] {
            get { return Segment[index]; }
            set { Segment[index] = value; }
        }

        public int OffSet {
            get { return Segment.offset; }
        }

        public bool Equals(MessageContext source) {
            if (!Segment.Equals(source.Segment)) return false;
            if (Socket != null && source.Socket != null) return Socket.Equals(source.Socket);
            return Socket == source.Socket;
        }

        public new string ToString() {
            return Segment.array.Concat(",");
        }
    }
}